﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplicationSHNETII
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            
            btnCalculate.IsEnabled = false;
            Calculate();
            btnCalculate.IsEnabled = true;
            //tbResult.Text = String.Empty;

            //int min = 0;

            //try
            //{
            //    min = Int32.Parse(txtMin.Text);
            //}
            //catch(Exception exception)
            //{
            //    tbResult.Text = exception.Message;
            //    min = -1;
            //}
            //finally
            //{
            //    tbResult.Text += String.Format("{0}{1}", Environment.NewLine, min);
            //}
        }

        private void Calculate()
        {
            tbResult.Text = String.Empty;

            int min, max, count;

            if (Int32.TryParse(txtMin.Text, out min) && 
                Int32.TryParse(txtMax.Text, out max) && 
                Int32.TryParse(txtCount.Text, out count))
            {

                var array = GetRandomArray(min, max, count);
                double result;
                var t = SumN(array, 7, out result);

                tbResult.Text = String.Format("Sum of pow n: {0}\nElapsed Time: {1}", result, t.TotalMilliseconds);
            }
            else
            {
                tbResult.Text = "Parse Error";
            }
        }

        private TimeSpan SumN(int[] array, int n, out double result) 
        {
            var start = DateTime.Now;
            result = 0.0;

            foreach (var item in array)
            {
                result = Math.Pow(item, n);
            }

            return DateTime.Now - start;
        }

        private int[] GetRandomArray(int min, int max, int count)
        {
            Random rnd = new Random();
            int[] array = new int[count];

            for (int i = 0; i < count; i++)
            {
                array[i] = rnd.Next(min, max);
            }

            return array;
        }
    }
}
